package cc.eddic.pratice.programmingparadigms.emp01array.impl;

import cc.eddic.pratice.programmingparadigms.Employee;
import cc.eddic.pratice.programmingparadigms.Result;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class StatisticsGcsInnerClassImpl extends StatisticsGcsImpl {
    @Override
    public Result[] pivotByGender(Employee[] employees) {
        return countBy(employees, new GroupKeyGenderExtractor());
    }

    @Override
    public Result[] pivotByDepartment(Employee[] employees) {
        return countBy(employees, new GroupKeyDepartmentExtractor());
    }

    @Override
    public Result[] pivotByJobTitle(Employee[] employees) {
        return countBy(employees, new GroupKeyExtractor() {
            @Override
            public String getKey(Employee employee) {
                return employee.getJobTitle();
            }
        });
    }

    private Result[] countBy(final Employee[] employees, final GroupKeyExtractor fieldExtractor) {
        int index = 0;
        Result[] results = new Result[employees.length];
        for (Employee employee : employees) {
            String key = fieldExtractor.getKey(employee);

            boolean isFound = false;
            // 如果已经存在，则加 1
            for (Result result : results) {
                if (null == result) {
                    break;
                }
                if (result.getKey().equals(key)) {
                    isFound = true;
                    result.inc();
                }
            }
            // 如果不存在，添加，初始值为 1
            if (!isFound) {
                results[index++] = new Result(key);
            }
        }
        // 返回实际数量的数组
        Result[] newResults = new Result[index];
        for (int i = 0; i < index; i++) {
            newResults[i] = results[i];
        }
        // 数量倒排序
        bubbleSort(newResults);
        return newResults;
    }


    interface GroupKeyExtractor {
        String getKey(Employee employee);
    }

    @Slf4j
    static class GroupKeyGenderExtractor implements GroupKeyExtractor {
        @Override
        public String getKey(Employee employee) {
            log.debug("GroupKeyGenderExtractor: {}", employee.toString());
            return employee.getGender();
        }
    }

    @Slf4j
    static class GroupKeyDepartmentExtractor implements GroupKeyExtractor {
        @Override
        public String getKey(Employee employee) {
            log.debug("GroupKeyDepartmentExtractor: {}", employee.toString());
            return employee.getDepartment();
        }
    }
}
